package com.api.shopapi.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.oa.utils.LocalRedis;
import com.api.shopapi.common.HttpClientUtil;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.Error;
import com.api.shopapi.entity.dto.GoodsPriceDTO;
import com.api.shopapi.service.*;
import com.zhaofujun.automapper.AutoMapper;
import com.zhaofujun.automapper.IMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.codec.binary.Base64;

/**
 * 基类
 */

public class BaseController {


    @Autowired
    RestTemplate restTemplate;

    @Value("${appKey}")
    public String privateKey;

    @Autowired
    @Qualifier("ErrorServiceImplOne")
    private ErrorService errorService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("GoodsServiceImplOne")
    private GoodsService goodsService;

    @Autowired
    @Qualifier("GoodsPriceServiceImplOne")
    private GoodsPriceService goodsPriceService;

    @Autowired
    @Qualifier("CartGoodsPriceServiceImplOne")
    private CartGoodsPriceService cartGoodsPriceService;

    @Autowired
    @Qualifier("InterfaceServiceImplOne")
    protected InterfaceService interfaceService;

    @Autowired
    @Qualifier("RoleServiceImplOne")
    protected RoleService roleService;


    final SimpleDateFormat sdfYMD = new SimpleDateFormat("yyyy-MM-dd");
    final SimpleDateFormat sdfYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    protected String emptyUUID = "00000000-0000-0000-0000-000000000000";
    protected IMapper mapper = new AutoMapper();


    @Value("${my.rootPath}")
    protected String rootPath;

    @Value("${my.imgsRootPath}")
    protected String imgsRootPath;

    @Value("${my.filesRootPath}")
    protected String filesRootPath;

    @Value("${my.thread}")
    protected String path;

    @Value("${my.push}")
    protected String push;

    @Value("${my.elderlyAlarm}")
    protected String pushAlarmPath;


    @Value("${my.pushBusiness}")
    protected String pushBusiness;

    @Value("${my.pushServe}")
    protected String pushServe;

    @Value("${my.pushUser}")
    protected String pushUser;

    @Value("${my.pushSOS}")
    protected String pushSOS;


    @Value("${my.tencentMapKey}")
    protected String tencentMapKey;

    @Value("${my.error}")
    protected String errorPath;

    @Value("${my.qrCodePath}")
    protected String keepPath;//保存地址

    @Value("${my.shareAddress}")
    protected String jumpPath;//跳转地址


    @Value("${thisUrl}")
    protected String thisUrl;

    @Value("${deviceApi}")
    protected String deviceApi;

    @Value("${server.port}")
    protected String port;


    protected Boolean checkSignForOut(String timeStr, String sign) {
//        String key = "123456";
//        String formatStr = String.format("timeStr=%s&key=%s", timeStr, key);
//        String md5Str = getMD5Str(formatStr);
//        return sign.equals(md5Str);
        return true;
    }


    //接口入口检查(废弃)
    protected PreCheck PreCheck(String timeStr, String sign) {
//        if(!checkSignPC(timeStr,sign)){
//            return new PreCheck(1,"签名错误");
//        }
//
//        if(1 == 2){
//            return new PreCheck(1,"接口已暂停");
//        }


        return new PreCheck(0, "");
    }

    //签名校验(废弃)
    protected Boolean checkSignPC(String timeStr, String sign) {
//        String key = "ED139FA9132F1E60967C8579D1F7B958";
//        String formatStr = String.format("timeStr=%s&key=%s", timeStr, key);
//        String md5Str = getMD5Str(formatStr);
//        return sign.equals(md5Str);
        return true;
    }

    @Autowired
    @Qualifier("InterfaceTimeServiceImplOne")
    private InterfaceTimeService interfaceTimeService;


    //完成返回
    protected MyResult success(Object data) {
        return MyResult.Success(data);
    }

    //未完成返回
    protected MyResult failed(String message) {
        return MyResult.Failed(message);
    }

    //异常返回
    protected MyResult anomalous(String message) {
        //异常
        InterfaceTime interfaceTime = new InterfaceTime();
        interfaceTime.setInterfaceTimeCode(IdUtil.fastSimpleUUID());
        interfaceTime.setCreateTime(DateUtil.date());
        interfaceTime.setUseTime(0);
        interfaceTime.setInterface(message);
        interfaceTimeService.insert(interfaceTime);
        return MyResult.Anomalous(message);
    }


    //签名校验
    protected Boolean checkSignInterface(String timeStr, String sign, String method) {

        HttpServletRequest request =
                ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                        .getRequest();

        String ip = getIpAddress(request);
        System.out.println(ip + ":" + method);


        String key = "ED139FA9132F1E60967C8579D1F7B958";
        String formatStr = String.format("timeStr=%s&key=%s", timeStr, key);
        String md5Str = getMD5Str(formatStr);
        return sign.equals(md5Str);
    }

    //接口入口检查（后台接口）
    protected PreCheck checkSignAdmInterface(String timeStr, String sign, String staffCode, String method) {

//        if(!checkSignInterface(timeStr,sign,method)){
//            return new PreCheck(1,"签名错误");
//        }
//
//        Staff staff = staffService.getByStaffCode(staffCode);
//        if(staff == null){
//            return new PreCheck(1,"职工不存在");
//        }
//
//
//        //RoleGovernment role = roleGovernmentService.getByRoleCode(staff.getRoleCode());
//        Role role = roleService.getByRoleCode(staff.getRoleCode());
//        if(role == null){
//            return new PreCheck(1,"职工角色不存在");
//        }
//
//        Interface interface2 = interfaceService.getByInterfaceCode("4216ae99-7505-426a-9fd3-45245c3cb75d");
//        if(interface2 != null){
//            if(interface2.getTag() == 0){
//
//            }else{
//                System.out.println("接口已关闭");
//                return new PreCheck(1,"接口已关闭");
//            }
//        }else{
//            System.out.println("读取接口配置失败");
//            return new PreCheck(1,"读取接口配置失败");
//        }

        return new PreCheck(0, "");
    }

    //接口入口检查 （前端/App接口）
    protected PreCheck checkSignFrontInterface(String timeStr, String sign, String method) {
//        if(!checkSignInterface(timeStr,sign,method)){
//            return new PreCheck(1,"签名错误");
//        }
//
//
//        Interface interface2 = interfaceService.getByInterfaceCode("4216ae99-7505-426a-9fd3-45245c3cb75d");
//        if(interface2 != null){
//            if(interface2.getTag() == 0){
//
//            }else{
//                System.out.println("接口已关闭");
//                return new PreCheck(1,"接口已关闭");
//            }
//        }else{
//            System.out.println("读取接口配置失败");
//            return new PreCheck(1,"读取接口配置失败");
//        }

        return new PreCheck(0, "");
    }


    //获取签名
    protected String getSign(String timeStr) {
        String key = "ED139FA9132F1E60967C8579D1F7B958";
        String formatStr = String.format("timeStr=%s&key=%s", timeStr, key);
        String md5Str = getMD5Str(formatStr);
        return md5Str;
    }

    protected String getSign2(String timeStr) {
        String key = "ED139FA9132F1E60967C8579D1F7B958";
        String formatStr = String.format("timestr=%s&key=%s", timeStr, key);
        String md5Str = getMD5Str(formatStr);
        return md5Str;

    }


    //md5 加密
    protected String getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }

    //获取时间戳
    protected String getTimeStr() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    //获取时间戳毫秒
    protected String getTimeStrSSS() {
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    }


    //获取计算机初始时间
    protected Date getInitTime() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse("1970-01-01 08:00:00");
        } catch (Exception e) {
            e.printStackTrace();
            return new Date();
        }
    }

    //获取时间戳毫秒
    protected String getTimeStrSSSRandom() {
        String ss = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        Random random = new Random();
        int k = random.nextInt(1000000);
        return ss + "-" + k;
    }

    //判断是否是支持的图片格式
    protected Boolean isImg(String fileName) {
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf).toLowerCase();

        if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png")) {
            return true;
        }
        return false;
    }

    //判断是否是支持的文件格式
    protected Boolean isFile(String fileName) {
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf).toLowerCase();

        if (suffix.equals(".mp4") || suffix.equals(".mp3") || suffix.equals(".doc") || suffix.equals(".docx") || suffix.equals(".xls") || suffix.equals(".xlsx") || suffix.equals(".pdf")) {
            return true;
        }
        return false;
    }

    //获取文件的扩展名
    protected String getSuffix(String fileName) {
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf);
        return suffix;
    }


    /**
     * 获取真实ip地址，避免获取代理ip
     */
    protected String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    //手机格式判断
    protected Boolean isPhone(String phone) {
        if (phone.length() == 11) {
            return true;
        } else {
            return false;
        }
    }

    //身份证格式判断
    protected Boolean isIdCard(String idCard) {
        if (idCard.length() == 18) {
            return true;
        } else {
            return false;
        }
    }

    //往文件里写东西
    protected static void saveAsFileWriter(String filePath, String content) {
        FileWriter fwriter = null;
        try {
            // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
            fwriter = new FileWriter(filePath);
            fwriter.write(content);

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    //删除文件
    protected static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }


    //post restTemplate 请求
    protected String postTemplate(String url, HashMap<String, Object> params) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //headers.set("phone", "123456");

        //Map<String, Object> params = new HashMap<>();
        //params.put("name", "yyc");
        //params.put("email", "12306");


        HttpEntity httpEntity = new HttpEntity(params, headers);


        ResponseEntity<String> request = restTemplate.postForEntity(url, httpEntity, String.class);


//        System.out.println(request.getBody());

        return request.getBody();
    }


    //get restTemplate 请求
    protected String getTemplate(String url) {
        return restTemplate.getForObject(url, String.class);
    }


    //路由分发
    protected MyResult myRouter(String url, JSONObject jsonObject) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String content = jsonObject.toJSONString();
        HttpEntity<String> request = new HttpEntity<>(content, headers);

        //String url = "http://SERVICE-USER/staff/List";
        ResponseEntity<MyResult> postForEntity = restTemplate.postForEntity(url, request, MyResult.class);

        return postForEntity.getBody();
    }


    //获取异常的详细信息
    protected String getExceptionMsg(Exception e) {

        String str = e.getMessage() + "\n";

        StackTraceElement[] messages = e.getStackTrace();
        int length = messages.length;
        for (int i = 0; i < length; i++) {

            //System.out.println("ClassName:"+messages[i].getClassName());
            //System.out.println("getFileName:"+messages[i].getFileName());
            //System.out.println("getLineNumber:"+messages[i].getLineNumber());
            //System.out.println("getMethodName:"+messages[i].getMethodName());
            //System.out.println("toString:"+messages[i].toString());

            //str += "ClassName:"+messages[i].getClassName();
            //str += "getMethodName:"+messages[i].getMethodName();
            //str += "getLineNumber:"+messages[i].getLineNumber()+"\n";

            str += messages[i].toString() + "\n";


        }
        e.printStackTrace();
        return e.getMessage();
    }


    //获取异常的详细信息
    protected void insertError(String url, String param, String message, String type) {
        Error error = new Error();
        error.setErrorCode(UUID.randomUUID().toString());
        error.setUrl(url);
        error.setParam(param);
        error.setMessage(message);
        error.setType(type);
        error.setCreateTime(new Date());
        int k = errorService.insert(error);
        System.out.println(k);
    }

    //获取异常的详细信息(事务)
    protected void insertErrorForAffair(String url, JSONObject jsonObject, Exception e) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        File file1 = new File(errorPath);
        if (!file1.exists()) {//如果文件夹不存在
            file1.mkdir();//创建文件夹
        }
        String filePath = errorPath + "\\" + format.format(new Date()) + ".txt";
        String content = url + jsonObject.toJSONString() + "!" + getExceptionMsg(e) + "!" + "api";
        //saveAsFileWriter(filePath,content);
    }


    //腾讯根据经纬度获取地址
    public String getAddressByLonLat(String lon, String lat) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lon + "&key=" + tencentMapKey;
        String rv = getTemplate(url);
        return rv;
    }

    public static void main(String[] args) {
        double lon = 117.266463;
        double lat = 31.862285;
        double tx_lat;
        double tx_lon;
        double x_pi = 3.14159265358979324;
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        tx_lon = z * Math.cos(theta);
        tx_lat = z * Math.sin(theta);
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        String url = "https://apis.map.qq.com/ws/geocoder/v1";
        String param = "location=" + tx_lat + "," + tx_lon + "&key=TROBZ-EKEKJ-I7SFK-KO75D-DD265-5BF4O";
        String s = httpClientUtil.sendHttpPost(url, param);
        System.out.println(s);
    }


    protected String readTxt(String filePath) {
        String str2 = "";
        try {
            File f1 = new File(filePath);// 打开文件

            FileInputStream in = new FileInputStream(f1);
            // 指定读取文件时以UTF-8的格式读取
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); // 读取文件

            String str;
            while ((str = br.readLine()) != null) {
                str2 = str;
            }

            in.close();// 关闭读取
        } catch (Exception e1) {// 如果有错误，这里进行处理
            e1.printStackTrace();// 打印错误信息
        }
        return str2;
    }


    //--------------------获取商品价格------------------------------

    //获取商品的价格
    protected double GetPrice(String goodsCode, JSONArray goodsAttributeCodesArg, JSONArray goodsAttributeCodesValueArg) {

        Goods goods = goodsService.getByGoodsCode(goodsCode);

        String goodsAttributeCodesStr = goods.getGoodsAttributeCodes();
        String[] goodsAttributeCodesArr = null;
        if (goodsAttributeCodesStr.equals("") || goodsAttributeCodesStr == null || goodsAttributeCodesStr.equals("null")) {
            goodsAttributeCodesArr = new String[0];
        } else {
            goodsAttributeCodesArr = goodsAttributeCodesStr.split(",");
        }


        List<GoodsPriceDTO> listGoodsPriceDTO = goodsPriceService.getByGoodsCode(goodsCode);


        //根据价格排序
        listGoodsPriceDTO.sort(Comparator.comparing(GoodsPriceDTO::getPrice));


        //属性code是否齐全
        Boolean attributeCodeIsAll = true;

        if (goodsAttributeCodesArg.size() != goodsAttributeCodesArr.length) {
            attributeCodeIsAll = false;
        }
        if (attributeCodeIsAll) {
            for (int i = 0; i < goodsAttributeCodesArg.size(); i++) {
                String codeItem = goodsAttributeCodesArg.get(i).toString();
                if (!goodsAttributeCodesStr.toLowerCase().contains(codeItem.toLowerCase())) {
                    attributeCodeIsAll = false;
                }
            }
        }

        if (!attributeCodeIsAll) {
            return 0.0;
        }


        //存储完全匹配的记录
        GoodsPriceDTO goodsPriceDTOSelect = null;


        //遍历每一条记录
        for (GoodsPriceDTO goodsPriceDTO : listGoodsPriceDTO) {

            //存储完全匹配的记录的标识
            Boolean bTop = true;

            //变量属性Code数组
            for (int i = 0; i < goodsAttributeCodesArg.size(); i++) {

                //检查本条记录是否存在该键值
                Boolean b = haveThis(goodsPriceDTO, goodsAttributeCodesArg.getString(i),
                        goodsAttributeCodesValueArg.getString(i));

                System.out.println("b = " + b);

                //不存在该键值
                if (!b) {

                    //完全匹配的记录的标识设为false
                    bTop = false;

                    //退出剩余的检查
                    break;
                }
            }


            //完全匹配的记录的标识设为true
            if (bTop) {

                //筛选到匹配的记录
                goodsPriceDTOSelect = goodsPriceDTO;

                //退出剩余的检查
                break;
            }

        }

        if (goodsPriceDTOSelect == null) {
            return 0.0;
        } else {
            return goodsPriceDTOSelect.getPrice();
        }

    }


    //本条记录里是否存在该键值
    private Boolean haveThis(GoodsPriceDTO goodsPriceDTO, String attributeCode, String attributeValue) {


        //首字母改成大写
        attributeCode = attributeCode.substring(0, 1).toUpperCase() + attributeCode.substring(1);


        //循环父类的属性
        Class superClass = goodsPriceDTO.getClass().getSuperclass();
        while (superClass != null) {
            Field[] superFileds = superClass.getDeclaredFields();
            for (int i = 0; i < superFileds.length; i++) {
                String name = superFileds[i].getName();
                Object obj = getFieldValueByName(name, goodsPriceDTO);
                String value = obj == null ? "" : obj.toString();
                if (name.equals(attributeCode) && value.equals(attributeValue)) {
                    return true;
                }

            }
            superClass = superClass.getSuperclass();
        }

        //变量本类的属性
        Field[] allFields2 = goodsPriceDTO.getClass().getDeclaredFields();
        for (int i = 0; i < allFields2.length; i++) {
            String name = allFields2[i].getName();
            Object obj = getFieldValueByName(name, goodsPriceDTO);
            String value = obj == null ? "" : obj.toString();

            if (name.equals(attributeCode) && value.equals(attributeValue)) {
                return true;
            }

        }


        return false;
    }


    //使用反射根据属性名称获取属性值
    protected Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            System.out.println("属性不存在");
            return null;
        }
    }

    //获取对象属性，返回一个字符串数组
    private String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    //通过上面两个步骤，即可将一个对象转化为一个数组
    private Object[] getFiledValues(Object o) {
        String[] fieldNames = this.getFiledName(o);
        Object[] value = new Object[fieldNames.length];
        for (int i = 0; i < fieldNames.length; i++) {
            value[i] = this.getFieldValueByName(fieldNames[i], o);
        }
        return value;
    }


    //----------------判断CartGoodsPrice表中是否存在---------------------

    //判断购物车中给定属性的商品是否已存在
    protected Boolean hadCartGoodsPriceExist(String cartGoodsCode, JSONArray goodsAttributeCodesArg,
                                             JSONArray goodsAttributeCodesValueArg) {


        CartGoodsPrice cartGoodsPrice = cartGoodsPriceService.getByCartGoodsCode(cartGoodsCode);


        //存储完全匹配的记录的标识
        Boolean bTop = true;

        //变量属性Code数组
        for (int i = 0; i < goodsAttributeCodesArg.size(); i++) {

            //检查本条记录是否存在该键值
            Boolean b = haveThis2(cartGoodsPrice, goodsAttributeCodesArg.getString(i),
                    goodsAttributeCodesValueArg.getString(i));


            //不存在该键值
            if (!b) {

                //完全匹配的记录的标识设为false
                bTop = false;

                //退出剩余的检查
                break;
            }
        }


        return bTop;

    }

    //本条记录里是否存在该键值
    private Boolean haveThis2(CartGoodsPrice cartGoodsPrice, String attributeCode, String attributeValue) {


        //首字母改成大写
        attributeCode = attributeCode.substring(0, 1).toUpperCase() + attributeCode.substring(1);


        //循环父类的属性
        Class superClass = cartGoodsPrice.getClass().getSuperclass();
        while (superClass != null) {
            Field[] superFileds = superClass.getDeclaredFields();
            for (int i = 0; i < superFileds.length; i++) {
                String name = superFileds[i].getName();
                Object obj = getFieldValueByName(name, cartGoodsPrice);
                String value = obj == null ? "" : obj.toString();
                if (name.equals(attributeCode) && value.equals(attributeValue)) {
                    return true;
                }

            }
            superClass = superClass.getSuperclass();
        }

        //变量本类的属性
        Field[] allFields2 = cartGoodsPrice.getClass().getDeclaredFields();
        for (int i = 0; i < allFields2.length; i++) {
            String name = allFields2[i].getName();
            Object obj = getFieldValueByName(name, cartGoodsPrice);
            String value = obj == null ? "" : obj.toString();

            if (name.equals(attributeCode) && value.equals(attributeValue)) {
                return true;
            }

        }


        return false;
    }


    //根据key获取对应的值
    protected String getValueByKey(String key, JSONArray goodsAttributeCodesArg,
                                   JSONArray goodsAttributeCodesValueArg) {

        String v = "";
        for (int i = 0; i < goodsAttributeCodesArg.size(); i++) {
            if (goodsAttributeCodesArg.get(i).toString().equals(key)) {
                v = goodsAttributeCodesValueArg.get(i).toString();
            }
        }

        return v;
    }

    //将字符串类型时间转换成date类型
    protected Date TimeStrToDate(String timeStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.parse(timeStr);
    }


    /**
     * 获取ip
     *
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }


    //string类型时间转Date()
    public static Date getTimeString(String time) {
        //DateFormat format= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = format.parse(time);
        } catch (Exception e) {

        }

        return date;
    }

    //根据日期判断星期几
    public static String getWeek(String dates) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = f.parse(dates);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        cal.setTime(d);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return getWeeks(w);
    }

    public static String getWeeks(int w) {
        String result = "";
        switch (w) {
            case 0:
                result = "星期日";
                break;
            case 1:
                result = "星期一";
                break;
            case 2:
                result = "星期二";
                break;
            case 3:
                result = "星期三";
                break;
            case 4:
                result = "星期四";
                break;
            case 5:
                result = "星期五";
                break;
            case 6:
                result = "星期六";
                break;
        }
        return result;
    }


    //base64字符串转byte[]
    protected byte[] base64String2ByteFun(String base64Str) {
        return Base64.decodeBase64(base64Str);
    }

    //byte[]转base64
    protected String byte2Base64StringFun(byte[] b) {
        return Base64.encodeBase64String(b);
    }


}

